package com.hy.service.impl;

import com.hy.bean.Comment;
import com.hy.bean.TableLike;
import com.hy.dao.CardDao;
import com.hy.service.CardService;
import com.hy.utils.FileUtils;
import com.hy.utils.ResponseResult;
import com.hy.utils.ResultUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CardServiceImpl implements CardService {
    private CardDao cardDao = new CardDao();

    @Override
    public void selectFollow(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer id = Integer.valueOf(request.getParameter("id"));
        Integer limit = Integer.valueOf(request.getParameter("limit"));

        List<Map<String, Object>> mapList = cardDao.selectFollow(id, limit);
        ResponseResult<List<Map<String, Object>>> result = new ResponseResult<>(200, "数据", mapList, 101);
        ResultUtils.result(result, request, response);
    }

    @Override
    public void selectCard(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer id = Integer.valueOf(request.getParameter("id"));
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        String title = request.getParameter("title");
        List<Map<String, Object>> cards = cardDao.selectCard(limit, title);
        ResponseResult<List<Map<String, Object>>> result = new ResponseResult<>(200, "数据", cards, 101);
        ResultUtils.result(result, request, response);
    }

    @Override
    public void selectRecommend(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer id = Integer.valueOf(request.getParameter("id"));
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        List<Map<String, Object>> cards = cardDao.selectRecommend(id, limit);
        ResponseResult<List<Map<String, Object>>> result = new ResponseResult<>(200, "数据", cards, 101);
        ResultUtils.result(result, request, response);
    }

    public void sum(List<Map<String,Object>> comments,Integer id) throws Exception {
        for (Map<String,Object> c:comments) {
            c.put("create_time",c.get("create_time").toString().substring(0,10));

            List<Map<String,Object>> childList = cardDao.selectCommentParentId((Integer) c.get("id"),id);
            c.put("childrenList",childList);

             sum((List<Map<String, Object>>) c.get("childrenList"),id);
        }
    }


    /**
     * 查询评论
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    public void selectComment(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int id = Integer.parseInt(request.getParameter("id"));
        List<Map<String,Object>> comments = cardDao.selectCommentParentId(0,id);
        for (Map<String,Object> c:comments) {
            c.put("create_time",c.get("create_time").toString().substring(0,10));
        }
        sum(comments,id);
        ResponseResult<?> result = new ResponseResult<>(200, "数据", comments, 101);
        ResultUtils.result(result, request, response);
    }
    @Override
    public void insertComment(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int cardId = Integer.parseInt(request.getParameter("cardId"));
        int parentId = Integer.parseInt(request.getParameter("parentId"));
        int userId = Integer.parseInt(request.getParameter("userId"));
        String commentContent = request.getParameter("commentContent");

        // 使用正则表达式提取img标签的src值
        String pattern = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
        Pattern imgPattern = Pattern.compile(pattern);
        Matcher matcher = imgPattern.matcher(commentContent);
        // 处理匹配到的每个img标签
        while (matcher.find()) {
            String originalSrc = matcher.group(1);
            // 保存图片到服务器的upload文件夹中
            ServletContext servletContext = request.getServletContext();
            String newSrc = FileUtils.saveImage(originalSrc,servletContext);
            // 更新content中的src值为新的路径
            commentContent = commentContent.replace(originalSrc, newSrc);
        }

        Comment comment = new Comment();
        comment.setCardId(cardId);
        comment.setParentId(parentId);
        comment.setUserId(userId);
        comment.setCommentContent(commentContent);
        comment.setCreateId(userId);
        boolean flag = cardDao.insertComment(comment);
        ResponseResult<?> result =null;
        if (flag){
            result =new ResponseResult<>(200, "数据", flag, 101);
        }else {
            result = new ResponseResult<>(200, "数据", flag, 102);
        }
        ResultUtils.result(result, request, response);
    }

    @Override
    public void selectCommentCount(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int cardId = Integer.parseInt(request.getParameter("cardId"));
        Long count = cardDao.selectCommentCount(cardId);
        ResponseResult<Long> result = new ResponseResult<>(200, "数据", count, 101);
        ResultUtils.result(result, request, response);
    }

    //帖子赞同数
    @Override
    public void selectEndorseCount(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int cardId = Integer.parseInt(request.getParameter("cardId"));
        Long count = cardDao.selectEndorseCount(cardId);
        ResponseResult<Long> result = new ResponseResult<>(200, "数据", count, 101);
        ResultUtils.result(result, request, response);
    }

    //赞同
    @Override
    public void updateEndorse(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int cardId = Integer.parseInt(request.getParameter("cardId"));
        int userId = Integer.parseInt(request.getParameter("userId"));
        String marker = request.getParameter("marker");
        boolean flag = cardDao.selectTabLike(cardId, userId);
        boolean flag02 = false;

        if (flag) {
            flag02 = cardDao.updateEndorse(cardId, userId, marker);
        } else {
            flag02 = cardDao.insertTabLike(cardId, userId, "1", "0", "0");
        }

        ResponseResult<Boolean> result = new ResponseResult<>(200, "数据", flag02, 101);
        ResultUtils.result(result, request, response);
    }

    //反对修改
    @Override
    public void updateOppose(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int cardId = Integer.parseInt(request.getParameter("cardId"));
        int userId = Integer.parseInt(request.getParameter("userId"));
        String marker = request.getParameter("marker");
        boolean flag = cardDao.selectTabLike(cardId, userId);
        boolean flag02 = false;

        if (flag) {
            flag02 = cardDao.updateOppose(cardId, userId, marker);
        } else {
            flag02 = cardDao.insertTabLike(cardId, userId, "0", "0", "0");
        }

        ResponseResult<Boolean> result = new ResponseResult<>(200, "数据", flag02, 101);
        ResultUtils.result(result, request, response);
    }

    //收藏修改
    @Override
    public void updateCollect(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int cardId = Integer.parseInt(request.getParameter("cardId"));
        int userId = Integer.parseInt(request.getParameter("userId"));
        String marker = request.getParameter("marker");
        boolean flag = cardDao.selectTabLike(cardId, userId);
        boolean flag02 = false;

        if (flag) {
            flag02 = cardDao.updateCollect(cardId, userId, marker);
        } else {
            flag02 = cardDao.insertTabLike(cardId, userId, "2", "1", "0");
        }

        ResponseResult<Boolean> result = new ResponseResult<>(200, "数据", flag02, 101);
        ResultUtils.result(result, request, response);
    }

    //喜欢修改
    @Override
    public void updateLove(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int cardId = Integer.parseInt(request.getParameter("cardId"));
        int userId = Integer.parseInt(request.getParameter("userId"));
        String marker = request.getParameter("marker");
        boolean flag = cardDao.selectTabLike(cardId, userId);
        boolean flag02 = false;

        if (flag) {
            flag02 = cardDao.updateLove(cardId, userId, marker);
        } else {
            flag02 = cardDao.insertTabLike(cardId, userId, "2", "0", "1");
        }

        ResponseResult<Boolean> result = new ResponseResult<>(200, "数据", flag02, 101);
        ResultUtils.result(result, request, response);
    }

    @Override
    public void selectTableLikeByCardId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int cardId = Integer.parseInt(request.getParameter("cardId"));
        int uid = Integer.parseInt(request.getParameter("uid"));
        TableLike tableLike = cardDao.selectTableLikeByCardId(cardId, uid);
        ResponseResult<TableLike> result = new ResponseResult<>(200, "数据", tableLike, 101);
        ResultUtils.result(result, request, response);
    }

    public void imgUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String method = request.getMethod();

        Part part = request.getPart("fileName");
            // 设置向客户端发送的内容类型
            response.setContentType("text/plain;charset=UTF-8");
            PrintWriter out = response.getWriter();
        if( part != null ) {
            // 获取用户上传的文件名称
            String filename = part.getSubmittedFileName();
            // 如果文件名称是存在的，则说明客户端发送了有效的文件
            if( filename != null && filename.trim().length() != 0 && part.getSize() > 0 ) {
                // 将接受到的文件保存到 @MultipartConfig 的 location 指定的位置
                part.write( filename );
                // 向客户端返回成功信息
                out.println( "{");
                out.println( "\"success\" : true ,");
                // 确定用于显示图片的 Servlet 路径 ( 与后文的 ImageShowServlet 对应 )
                final String path = "/image/upload/comment-imgs/" + filename ;
                out.println( "\"file_path\" : \"" + path + "\"");// 与Simditor一致
                out.println( "}");
                // 直接使用 return 语句结束方法
                return ;
            }
        }
        // 向客户端返回失败信息
        out.println( "{");
        out.println( "\"success\" : false");
        out.println( "}");
    }





}
